package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.AppealPicBean;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.ComplaintMoreInfoBean;
import com.sczmgk.hotline_pzh.entity.Picurls;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.view.MyGridView;
import com.sczmgk.hotline_pzh.view.TextItemView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/29 0029.
 */
public class WorkDetailActivity extends ComplaintDetailMoreInfomationActivity {

    /*更新ui发送的消息*/
    private final int REFRESH_LIST = 201;

    /*审核完成与待审核*/
    private static final int AUDIT_COMPLETED = 8;
    private static final int TO_AUDIT = 7;

    /*审核完成上传的图片集合*/
    private ArrayList<AppealPicBean> auditPics = new ArrayList<>();

    private AppealAdapter auditAdapter;

    /*投诉审核的状态选择按钮*/
    private RadioGroup mRgReview;

    /*投诉审核提交按钮*/
    private Button mBtnReview;


    private Intent getIntent;

    /*投诉审核的处理时间*/
    private TextItemView mProcessDate;

    /*是否属实*/
    private TextItemView mIsAudit;

    /*相关备注*/
    private TextView mRelatedNote;

    /*相关备注的输入控件*/
    private EditText mEtReviewNote;

    /*相关图片的容器以及控件*/
    private LinearLayout mAudioContainer;
    private MyGridView mGvAudioPic;

    /*投诉审核的类型(待审核或审核完成)*/
    private int audioType;

    private LinearLayout toAudit;
    private LinearLayout auditCompleted;

    /**
     * 投诉 id string 类型
     */
    private String complaintId;
    private LinearLayout mAudioImage;

    /**
     * 设置头
     */
    @Override
    public void setHeader() {
        setTitle(R.string.complaints_review);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    @Override
    public void initView() {
        super.initView();
        //初始化投诉审核的控件以及显示
        mLayoutInvest.setVisibility(View.VISIBLE);

        //待审核的控件
        toAudit = (LinearLayout) findViewById(R.id.ll_to_audit);

        //审核完毕的控件
        auditCompleted = (LinearLayout) findViewById(R.id.ll_review_is_completed);

        mAudioImage = (LinearLayout) findViewById(R.id.ll_audio_image_item);

        //获取传递flag标识
        getIntent = getIntent();

        toAudit.setVisibility(View.GONE);
        auditCompleted.setVisibility(View.GONE);

        //TODO 数据类型 根据类型区分待审核或审核完毕
        audioType = getIntent.getIntExtra(Constants.WORK_TYPE_DETAIL, -1);

        //更加传递的审核类型初始化控件和控件的显示
        if (audioType == AUDIT_COMPLETED) {
            toAudit.setVisibility(View.GONE);
            auditCompleted.setVisibility(View.VISIBLE);
            //审核完成
            initAuditView();
        } else if (audioType == TO_AUDIT) {
            toAudit.setVisibility(View.VISIBLE);
            auditCompleted.setVisibility(View.GONE);
            //待审核
            initReviewView();
        } else {
            //隐藏布局
            toAudit.setVisibility(View.GONE);
            auditCompleted.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化投诉完毕的图标
     */
    private void initAuditView() {

        //处理时间
        mProcessDate = (TextItemView) findViewById(R.id.tiv_investigation_process_date);
        //是否属实
        mIsAudit = (TextItemView) findViewById(R.id.tiv_investigation_isaudit);
        //相关备注
        mRelatedNote = (TextView) findViewById(R.id.tv_audio_note);
        //相关图片的容器
        mAudioContainer = (LinearLayout) findViewById(R.id.ll_appeal_audio_container);
        //相关图片
        mGvAudioPic = (MyGridView) findViewById(R.id.gv_appeal_audio_pic);

        //TODO 设置刷新数据数据
        //设置相关图片的Adapter
        auditAdapter = new AppealAdapter();
        mGvAudioPic.setAdapter(auditAdapter);

    }

    /**
     * 初始化待审核的控件
     */
    private void initReviewView() {

        //是否属实的RadioGroup
        mRgReview = (RadioGroup) findViewById(R.id.rg_review);
        //相关备注
        mEtReviewNote = (EditText) findViewById(R.id.et_review_note);
        //提交
        mBtnReview = (Button) findViewById(R.id.btn_review_submit);

        //设置情况是否属实的按钮选项
        mRgReview.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {

                RadioButton rbTrue = (RadioButton) mRgReview.getChildAt(0);
                RadioButton rbFalse = (RadioButton) mRgReview.getChildAt(1);

                switch (checkedId) {
                    case R.id.rb_review_true:
                        rbTrue.setChecked(true);
                        rbFalse.setChecked(false);
                        break;
                    case R.id.rb_review_false:
                        rbTrue.setChecked(false);
                        rbFalse.setChecked(true);
                        break;
                }
            }
        });

        //提交数据的按钮点击事件
        mBtnReview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //提交审核的数据
                initReviewData();
            }
        });
    }

    /**
     * 提交审核的数据
     */
    private void initReviewData() {

        int checkedRadioButtonId = mRgReview.getCheckedRadioButtonId();
        int isAudio = 1;
        switch (checkedRadioButtonId) {
            case R.id.rb_review_true:
                isAudio = 1;
                break;
            case R.id.rb_review_false:
                isAudio = 0;
                break;
        }

        String inputNote = mEtReviewNote.getText().toString().trim();
        if (Tools.isEmpty(inputNote)) {
            MyToast.show(WorkDetailActivity.this, "备注不能为空");
            return;
        }

        uploadData(isAudio, inputNote);

    }


    /**
     * 弹出提交成功的提示框
     */
    private void showDialog() {
        DialogFactory.warningDialog(WorkDetailActivity.this, R.string.audit_submit_success, R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        //如果是投诉详情跳转的界面,通过传递的id查询网络投诉数据
        complaintId = getIntent.getStringExtra(Constants.WORK_DETAIL);
        //设置相关图片的Adapter
        Map<String, Object> infos = new HashMap<>();
        infos.put("id", complaintId);
        infos.put("imei", MyApp.imei);
        if (loadingDialog != null) {
            DialogFactory.showDialog(loadingDialog);
        }

        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.GET_WORK_COMPLAIN, infos, MyHttp.GET, this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {

                DialogFactory.dismissLoadingDialog(loadingDialog);

                try {
                    paserInfoJson(dataRaw, isCache);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(WorkDetailActivity.this, mError.msg);
            }
        }, new HttpFailCallback() {
            @Override
            public void onServiceErrorCallback() {
//                MyToast.show(WorkDetailActivity.this, "您的网络有问题,请检查您的网络");
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }
        });

    }

    /**
     * 处理投诉详情的Json数据
     *
     * @param dataRaw
     * @param isCache
     */
    private void paserInfoJson(String dataRaw, boolean isCache) {

        if (Tools.isEmpty(dataRaw)) {
            MyLog.i("获取投诉详情数据", "get complaint detail json error");
            return;
        }

        //解析投诉详情的Json数据并存入JavaBean中
        Gson gson = new Gson();
        complaintMoreInfoBean = gson.fromJson(dataRaw, ComplaintMoreInfoBean.class);

        //发送消息更新ui
        mHandler.sendEmptyMessage(COMPLAINT_DETAIL);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case REFRESH_LIST:

                break;
            case COMPLAINT_DETAIL:
                //更改投诉详情ui
                refreshUi();
                break;
        }
    }

    /**
     * 刷新审核完毕的ui
     */
    private void refreshAuditUi() {

        String remarkText = Tools.replaceBr(complaintMoreInfoBean.stepcontent);

        //设置处理时间,是否属实以及备注
        mProcessDate.setText(complaintMoreInfoBean.stepptime);
        mIsAudit.setText(complaintMoreInfoBean.ispass == 1 ? "是" : "否");
        mRelatedNote.setText(remarkText);

        //设置图片
        List<Picurls> picurls = complaintMoreInfoBean.steppicurls;
        if (picurls != null && picurls.size() > 0) {
            auditPics = getAppealList(picurls);
            auditAdapter.setPicList(auditPics);
            auditAdapter.notifyDataSetChanged();
        } else {
            mAudioImage.setVisibility(View.GONE);
        }
    }

    /**
     * 刷新投诉详情ui
     */
    @Override
    public void refreshUi() {
          super.refreshUi();

        if (audioType == AUDIT_COMPLETED) {
            refreshAuditUi();
        }

    }


    @Override
    public boolean getIsNeedLogin() {
        return true;
    }


    /**
     * 提交审核数据
     *
     * @param isAudio   是否属实
     * @param inputNote 输入的备注信息
     */
    private void uploadData(final int isAudio, final String inputNote) {



            uploadFile(new OnUploadCallback() {
                @Override
                public void onUploadSuccess() {

                    //替换文本中的换行符和回车键
                    String resultContent = Tools.replaceNewLine(inputNote);

                    MyLog.d(TAG, "图片上传完成了，图片的路径是： " + getUploadFileUrls());
                    Map<String, Object> maps = new HashMap<>();

                    DialogFactory.showDialog(loadingDialog);
                    maps.put("userid", CacheUtils.getIntData(WorkDetailActivity.this, Constants.LOGIN_UID, 0));
                    maps.put("id", complaintId);
                    maps.put("remark", resultContent);
                    maps.put("ispassed", isAudio);
                    maps.put("picurls" , getUploadFileUrls()) ;
                    maps.put("videourl" , videoUrl == null ? "" : videoUrl) ;
                    maps.put("audiourl" , audioUrl == null ? "" : audioUrl) ;
                    MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.POST_CHECK_COMPLAIN, maps, MyHttp.POST, WorkDetailActivity.this,
                            false, null,
                            new SimplePaserJsonCallback() {

                                @Override
                                public void onVerifySuccess(String dataRaw, boolean isCache) {
                                }

                                @Override
                                public void onVerifyIsNull() {

                                    if (!isFinishing()) {
                                        DialogFactory.dismissLoadingDialog(loadingDialog);
                                        showDialog();
                                        uploadfileUrls.clear();//清除url
//                                        setResult(RESULT_OK, new Intent().putExtra(Constants.ONLINE_COMPLAINT_FLAG_NAME, Constants.ONLINE_COMPLAINT_FLAG));
                                        finish();
                                    }
                                }

                                @Override
                                public void onErrorCodeError(BaseEntity.MyError mError) {
                                    DialogFactory.dismissLoadingDialog(loadingDialog);
                                    DialogFactory.warningDialog(WorkDetailActivity.this, mError.msg);
                                }

                            }, new HttpFailCallback() {
                                @Override
                                public void onServiceErrorCallback() {
                                    DialogFactory.dismissLoadingDialog(loadingDialog);
                                }
                            });
                }
            });

    }

}
